<template>
  <div class="change-request-form">
    <el-container>
      <el-header class="form-header" height="22">
        <div class="header-text">Change Request Form</div>
      </el-header>
      <el-main class="container-main">
        <el-form>
          <submission-detail
            ref="submissionDetail"
            :submissionDetailData.sync="submissionDetailData"
            :compareChangeRequirementData="changeRequirementData">
          </submission-detail>

          <change-requirement
            ref="changeRequirement"
            class="form-padding"
            :compareStatusManagementData="statusManagementData"
            :compareSubmissionDetailData="submissionDetailData"
            :changeRequirementData.sync="changeRequirementData">
          </change-requirement>

          <task-form
            ref="taskForm"
            class="form-padding"
            :taskFormData.sync="taskFormData"
            :changeRequirementData="changeRequirementData">
          </task-form>

          <supplementary-information
            ref="supplementary"
            class="form-padding"
            :supplementaryData.sync="supplementaryData">
          </supplementary-information>

          <attachment-upload
            ref="attachmentUpload"
            class="form-padding"
            :uploadUrl="uploadUrl"
            :downloadUrl="downloadUrl"
            :acceptFileType="acceptFileType"
            :fileSizeLimit="fileSizeLimit">
          </attachment-upload>

          <el-form-item class="submit-form">
            <el-button type="primary" @click="submitAllForm">Submit</el-button>
            <el-button @click="cancelForm">Cancel</el-button>
          </el-form-item>
        </el-form>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import Bus from '@/common/js/eventBus'
import submissionDetail from './form-modules/SubmissionDetail.vue'
import changeRequirement from './form-modules/ChangeRequirement.vue'
import { createRequestFormMapping } from '@/common/js/requestForm'
import requestFormService from '@/service/requestForm'
import userService from '@/service/user'
import taskForm from './form-modules/TaskForm'
import supplementaryInformation from './form-modules/SupplementaryInformation.vue'
import attachmentUpload from '@/base-components/attachment-upload/AttachmentUpload.vue'
import moment from 'moment'
import constants from '@/common/js/constants'
import { REQUEST_FORM } from '@/store/namespaces'
import { createNamespacedHelpers } from 'vuex'

const {mapActions} = createNamespacedHelpers(REQUEST_FORM)

export default {
  name: 'ChangeRequestForm',
  components: {
    submissionDetail,
    changeRequirement,
    taskForm,
    supplementaryInformation,
    attachmentUpload
  },
  data() {
    return {
      statusManagementData: {
        pcrsStatusValue: '',
        inCharge: ''
      },
      riskAssessmentReviewData: {
        riskAssessmentReviewResult: '',
        riskAssessmentRemark: '',
        riskAssessmentProgress: ''
      },
      changeRequirementData: {
        changeMainCategory: '',
        changeMainCategoryList: [],
        changeSubCategory: '',
        changeSubCategoryList: [],
        productionPlatformInvolve: '',
        expectedDateChange: '',
        expectedTimeChange: {
          hours: '',
          minutes: '00'
        },
        secAdminReference: '',
        onlineServiceImpact: {
          fromDate: '',
          toDate: '',
          description: ''
        },
        isOnlineService: 'No',
        backendApplicationFunctionImpactDescription: '',
        isBackendApplication: 'No',
        systemPlatformImpactDescription: '',
        isSystemPlatform: 'No',
        isRiskLevel: false,
        riskLevel: '',
        riskAssessment: ''
      },
      submissionDetailData: {
        user: {
          requesterDomainId: '',
          requesterDisplayName: '',
          phone: '',
          email: ''
        },
        TTNo: '',
        splitedTTNos: [], // not need to deliver it to backend -- Mike Xie
        typeOfChange: '',
        classificationOfChange: '',
        ttPRLevel: '',
        endorserTeamId: null,
        endorserTeam: [],
        endorserArray: [],
        changeMainCategory: '',
        changeMainCategoryList: [],
        changeSubCategory: '',
        changeSubCategoryList: [],
        TTOrPRLevel: '',
        relatedPCRS: '',
        splitedPCRS: [],
        copyTo: '',
        changeObjective: '',
        submissionDate: moment(new Date()).format('DD-MMM-YYYY HH:mm')
      },
      taskFormData: {
        secondCoordinator: '',
        firstCoordinator: '',
        txt1stVerifierDomain: '',
        txt1stContactNumber: '',
        txt2ndVerifierDomain: '',
        txt2ndContactNumber: '',
        dateVerificationDeadline: '',
        workDuration: '',
        requestprocedures: [
          {
            procedureType: 'Working',
            procedureSeq: '',
            procedureDesc: '',
            handledBy: '',
            contactNo: '',
            taskStatus: '',
            taskRemark: ''
          },
          {
            procedureType: 'Recovery',
            procedureSeq: '',
            procedureDesc: '',
            handledBy: '',
            contactNo: '',
            taskStatus: '',
            taskRemark: ''
          },
          {
            procedureType: 'Verify',
            procedureSeq: '',
            procedureDesc: '',
            handledBy: '',
            contactNo: '',
            taskStatus: '',
            taskRemark: ''
          }],
        verifyDuration: '',
        recoveryDuration: '',
        is1stMoreThanOneParty: 'No',
        is2ndMoreThanOneParty: 'No',
        isRequireFallback: 'No',
        noFallbackActionReason: '',
        firstVerificationResult: 'None',
        firstVerificationReason: '',
        firstVerificationImpact: '',
        verificationResult: 'None',
        verificationReason: '',
        verificationImpact: ''
      },
      supplementaryData: {
        qaTestResult: '',
        approveQATestResult: '',
        ppTestResult: '',
        approvePPRunResult: '',
        testEnvironment: ''
      },
      attachments: [],
      formBaseData: {},
      functionList: {
        update_incharge: true
      },
      uploadUrl: '/rest/attachment/upload',
      downloadUrl: '/rest/attachment/download',
      acceptFileType: 'jpg,gif,png,bmp,doc,txt,pdf,docx,xls,xlsx,zip,msg,rtf,tif,html,htm,rar',
      fileSizeLimit: 1024
    }
  },
  created() {
    this.initUserInfo()
    this.setFormStatus(constants.CREATE_FORM)
    this.initBusEvents()
  },
  beforeDestroy() {
    this.removeBusEvents()
  },
  methods: {
    ...mapActions([
      'setFormStatus'
    ]),
    initUserInfo() {
      this.submissionDetailData.user = userService.getUser()
    },
    submitAllForm() {
      let refsList = ['submissionDetail', 'changeRequirement', 'taskForm', 'supplementary', 'attachmentUpload']
      let $this = this

      refsList.forEach((moduleName) => {
        this.$refs[moduleName].$refs['validatorForm'].validate((valid) => {
        })
      })

      setTimeout(async () => {
        // Check whether the page has css: el-icon-circle-close attributes
        let hasError = $this.$el.innerHTML.includes('el-form-item is-error')
        if (!hasError && $this.$refs['taskForm'].validateProcedureEditTable()) {
          const loading = this.$loading()
          this.taskFormData.requestprocedures = $this.$refs['taskForm'].getRequestProcedureData()
          this.attachments = this.$refs['attachmentUpload'].getAttachments()
          let postData = createRequestFormMapping(this.formBaseData, this.submissionDetailData, this.changeRequirementData,
            this.taskFormData, this.supplementaryData, this.attachments, this.statusManagementData, this.riskAssessmentReviewData)
          let responseData = await requestFormService.createSubmissionForm(postData)
          if (responseData.id) {
            $this.$alert(`Save Success, Ref No: ${responseData.refNO}`, {
              confirmButtonText: 'Close'
            }).then(_ => {
              // window.close()
            }).catch(_ => {})
          }
          loading.close()
        } else {
          this.$message({showClose: true, message: 'Missing Some Data Input', type: 'error'})
        }
      }, 300)
    },
    cancelForm() {
      window.close()
    },
    initBusEvents() {
      Bus.$on('validateTypeOfChange', () => {
        this.$refs['submissionDetail'].$refs['validatorForm'].validateField('typeOfChange')
      })
      Bus.$on('validateExpectedDateChange', () => {
        this.$refs['changeRequirement'].$refs['validatorForm'].validateField('expectedDateChange')
      })
    },
    removeBusEvents() {
      Bus.$off('validateTypeOfChange')
      Bus.$off('validateExpectedDateChange')
    }
  }
}
</script>

<style scoped lang="scss">
  @import './../../common/css/base.scss';

  .change-request-form {
    margin: 10px;
  }

  .container-main {
    border: 1px solid #5a9fd2;
  }

  .submit-form {
    margin-top: 20px;
    text-align: center;
  }

  .form-padding {
    margin-top: 10px;
  }

  .form-header {
    @include baseHeader(35px);
    font-size: 18px;
    background-color: $base-header-color;
  }

  .header-text {
    color: #fff;
    margin-top: 5px;
    font-weight: bold;
  }
</style>
